package luit.mmt02.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.mail.Message;

import luit.mmt02.R;
import luit.mmt02.adapter.attach_adapter;
import luit.mmt02.doituong.attach;
import luit.mmt02.doituong.showToast;
import luit.mmt02.mailControl.GmailControl;
import luit.mmt02.mailControl.HotmailControl;
import luit.mmt02.mailControl.YahooControl;
import luit.mmt02.secutity.AESControl;
import luit.mmt02.secutity.DEScontrol;
import luit.mmt02.secutity.KeyManager;
import luit.mmt02.secutity.RSAControl;
import luit.mmt02.secutity.TripleDEScontrol;
import luit.mmt02.secutity.webserviceRequest;
import luit.mmt02.xuly.ConvertMessageToList;
import luit.mmt02.xuly.XuLyChuoi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class attach_download_Activity extends Activity
{
	final static String ENC_PUBLIC = "ENC4";
	final static String ENC_AES = "AES";
	final static String ENC_DES = "DES";
	final static String ENC_TDES = "3DES";
	final static String ENC_FOOT = "@encrypt";
	final static String PUBLIC_KEY = "ENC4";
	final static String PATH_GET_KEY_DE = "/EncryptEmail/getkey_de/";
	final static String PATH_PUBLIC = "/EncryptEmail/keymail/";
	final static String PATH_FILE_DECRYPT = "/EncryptEmail/FileDecrypt/";
	final static String KEY_NGUOIGUI = "NGUOIGUI";
	final static String KEY_NGUOIGUI_NGUOINHAN = "KEY_NGUOIGUI_NGUOINHAN";
	final static String KEY_USERNAME = "username";
	final static String KEY_PASSWORD = "password";
	final static String KEY_LOAIEMAIL = "loai_email";
	final static String KEY_STR_ATTACH = "chuoi_attach";
	final static String KEY_STT = "_stt";
	final static String ENC1 = "enc1"; //des
	final static String ENC2 = "enc2"; //tdes
	final static String ENC3 = "enc3"; //aes
	final static String ENC4 = "enc4"; //aes
	ListView listview;
	List<attach>list;
    ArrayAdapter<attach>adapter;
    
    //
    int stt;
    String username;
    String password;
    Message []mess;
    ConvertMessageToList cv;
    XuLyChuoi xlchuoi ;
	String loai_email;
    GmailControl g;
    YahooControl y;
    HotmailControl h;
    String str_att;
    List<String>list_str_attach;
    String tag = "attach_download";
    showToast st;
    TextView txthelp;
    Button btn_down ;
    //
    String keyname; //loaikey ma hoa
	String loaimahoa; //loai ma hoa
	String input_aes,output_aes;
	
	KeyManager mykey;
	AESControl aes;
	DEScontrol des;
	TripleDEScontrol tdes;
	RSAControl rsa;
	int i_mahoa; //kiem tra co ma hoa
	String str_nguoigui;
	String str_pathkey,str_nguoigui_nguoinhan,str_loaimahoa,str_namekeyfile,progress,progress2;
	boolean flag_getkey,flag_decrypt_pri;
	String []array_attach; // mang chua cac file attach
	String Filein, Fileout;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.attach_layout);
		txthelp = (TextView) findViewById(R.id.txt_att_attachdown_help);
		btn_down = (Button) findViewById(R.id.btn_attach_down);
		mykey = new KeyManager();
		//
		st = new showToast(this);
		username = getIntent().getStringExtra(KEY_USERNAME);
		password = getIntent().getStringExtra(KEY_PASSWORD);
		loai_email = getIntent().getStringExtra(KEY_LOAIEMAIL);
		str_att = getIntent().getStringExtra(KEY_STR_ATTACH);
		stt = getIntent().getIntExtra(KEY_STT, -1);
		str_nguoigui = getIntent().getStringExtra(KEY_NGUOIGUI);
		str_nguoigui_nguoinhan = getIntent().getStringExtra(KEY_NGUOIGUI_NGUOINHAN);
		Log.v(tag, "ng gui - ngan:" +str_nguoigui_nguoinhan);
		array_attach = str_att.split(";");
		Log.v(tag, "Nhan duoc: " + username +";"+"nguoigui:" +str_nguoigui);
		//
		g = new GmailControl(username, password);
		y = new YahooControl(username, password);
		h = new HotmailControl(username, password);
		cv = new ConvertMessageToList();
		xlchuoi = new XuLyChuoi();
		//
		listview = (ListView)findViewById(R.id.lv_attach);
		list = new ArrayList<attach>();
		
		list_str_attach = xlchuoi.getList_str_attach(str_att);
		attach att = null;
		for(String str1 : list_str_attach)
		{
			if(!str1.equals("") && str1!= null )
				att = new attach(str1, true);
				Log.v(tag, "add att " + str1);
				list.add(att);
		}
		
		
		adapter = new attach_adapter(this, list);
		listview.setAdapter(adapter);
		i_mahoa = kiemtra_loaimahoa();
		giaima();
	}
	public void img_onClick(View v)
	{
		ImageButton img = (ImageButton)v;
		switch (img.getId()) {
		case R.id.img_attach_down_backA:
			finish();
			break;
		case R.id.img_attach_down_menu:
			openOptionsMenu();
			break;

		default:
			break;
		}
	}
	public void btn_onClick(View v)
	{
		Button btn = (Button)v;
		switch (btn.getId()) {
		case R.id.btn_attach_down:
			Log.v(tag, "dowbload");
			new save_async().execute("");
//			giaima();
			break;

		default:
			break;
		}
	}
	
	public void save_att()
	{
		try 
		{
			if(loai_email.startsWith("gmail"))
				mess = g.getmail();
			else if(loai_email.startsWith("yahoo"))
			{
				mess = y.getmail();
			}	//
			else if(loai_email.startsWith("hotmail"))
			{
				mess = h.getmail();
			}
			int i_down =  mess.length - stt;
//			Log.v(tag, mess[i_down].getSubject().toString());
			for(int i = 0 ; i < list.size(); i++)
			{
				if(list.get(i).isCheck())
				{
					Log.v(tag, "vao save _att");
					cv.Download_by_name(mess, i_down , i);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Err file download " + e.toString());
		}
	}
	
	private class save_async extends AsyncTask<String, Void, Void>
	{
		final ProgressDialog p = new ProgressDialog(attach_download_Activity.this);

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			String str_down = getResources().getString(R.string.downloading) + ": " + str_att;
			p.setMessage(str_down);
			p.show();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub
			Log.v(tag, "do in send .. async..");
			save_att();
			
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			
			p.dismiss();
			st.showmess(getResources().getString(R.string.down_success));
			continue_dialog();
			super.onPostExecute(result);
		}
		
	}
	
	public void open_forder_download()
	{
		try
		{
			AlertDialog.Builder buider = new AlertDialog.Builder(this);
			buider.setMessage("Open forder Download ...");
			buider.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			});
			buider.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					return;
				}
			});
			
			AlertDialog alert = buider.create();
			alert.show();
			
		}catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "err open_download " +e.toString());
		}
	}
	
	//menumenu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.attach_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.item_attach_down:
			new save_async().execute("");
			break;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public int kiemtra_loaimahoa()
	{
		String str_mess = "";
		int count = 0;
		try {
			String []arr_att = str_att.split(";");
			for(String str : arr_att)
			{
				String str1 = str.substring(str.length() - 4);
				Log.v(tag, "file ma hoa :" +str1);
				if(str1.equals(ENC1) || str1.equals(ENC2) || str1.equals(ENC3)
						||str1.equalsIgnoreCase(ENC4))
				{
					str_mess += str;
					str_mess += ";";
					count ++;
				}
			}
			String str_help = "";
			if(count > 0)
			{
				str_help = getResources().getString(R.string.count_file_encrypt) + str_mess;
//				btn_down.setText(getResources().getString(R.string.down_decrypt));
			}
			else
				str_help = getResources().getString(R.string.no_att);
			txthelp.setText(str_help);
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Loi kiem tra loai ma hoa");
		}
		return count;
	}
	
	public void giaima()
	{
		try {
			String []arr_att = str_att.split(";");
			for(String str : arr_att)
			{
				String str1 = str.substring(str.length() - 4);
				Log.v(tag, "loai ma hoa" +str1);
				if(str1.equals(ENC3))
				{
					keyname = Environment.getExternalStorageDirectory().getAbsolutePath() + "/keyaes.key";
					Log.v(tag, "chuoi att nhan dc " +str);
					input_aes = str; //str.substring(0, str.length()- 4);
					Log.v(tag, "chuoi sau khi cat: " + str.substring(0, str.length()- 5));
//					output_aes = str.substring(0, str.length()- 5) 
					output_aes = Environment.getExternalStorageDirectory().getAbsolutePath() + "/enc3.txt";
					File f = new File(output_aes);
					if(!f.isFile())
						f.createNewFile();
					Log.v(str, "giai ma aes");
					aes = new AESControl(mykey.getKeyAES(keyname));
					aes.DecFile(input_aes, output_aes);
					Log.v(str, "giai ma thanh cong");
				}else
				{
					Log.v(str, "khong phai ma hoa aes");
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.v(tag, "Loi giai ma " +e.toString());
		}
	}
	
	public void continue_dialog()  // dialog hoi co ma hoa file ko neu file co ma hoa, sau khi download file ve
 	{
 		try 
 		{
			AlertDialog.Builder builder = new Builder(this);
			builder.setMessage(getResources().getString(R.string.contunue_encrypt_file));
			String next = getResources().getString(R.string.Next);
			builder.setPositiveButton(next, new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					if(check_File_encrypt() > 0)
					{
						for(String str : array_attach)
						{
							Filein = str;
							str_loaimahoa = Filein.substring(Filein.length() - 4); //lay 4 ky tu duoi
							Log.v(tag, "continudialog: loai ma hoa:"+str_loaimahoa);
							if(str_loaimahoa.equalsIgnoreCase(ENC1) || str_loaimahoa.equalsIgnoreCase(ENC2)
									||str_loaimahoa.equalsIgnoreCase(ENC3) || str_loaimahoa.equalsIgnoreCase(ENC4))
							{
								
								
								decryptFile_action();
							}
						}
					}
					else
					{
						st.showmess("Khong co file nao ma hoa...");
					}
				}
			});
			builder.setNegativeButton(getResources().getString(R.string.Cancel), new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					
				}
			});
			
			AlertDialog alert = builder.create();
			alert.show();
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag + "-continue dialog", e.toString());
		}
 	}
	
	public void decryptFile_action()
	{
		try 
		{
			convert_str_loaimahoa();
			//
			Log.v(tag, " File in:" + Filein);
			String Folder_file_decrypt = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH_FILE_DECRYPT;
			File folder = new File(Folder_file_decrypt);
			if(!folder.isDirectory()) // neu ko ton tai forder
			{
				folder.mkdirs();
				Log.v(tag, " tao folder chua file ma hoa");
			}
			String nameFile = xlchuoi.get_name_attach(Filein);
			Fileout = Folder_file_decrypt + nameFile + ".de." + str_loaimahoa+ ".txt";
			File fo = new File(Fileout);
			if(!fo.isFile())
			{
				fo.createNewFile();
				Log.v(tag, "tao File out trong ...");
			}
			Log.v(tag, "File out : " + Fileout);
			//
			Log.v(tag, "decrypt File action: loaimahoa:" +str_loaimahoa);
			String path_de ;
			File savedirsub;
			flag_decrypt_pri = false;
			path_de = Environment.getExternalStorageDirectory().getAbsolutePath() + PATH_GET_KEY_DE;
			savedirsub = new File(path_de);
			if(!savedirsub.isDirectory())
			{
				Log.v(tag, "tao thu muc " + path_de);
				savedirsub.mkdirs();
			}
			else
				Log.v(tag, "da ton tai thu muc chua key, ko tao");
			
			str_namekeyfile = str_nguoigui_nguoinhan+" "+str_loaimahoa;////
		 		Log.v("str_namekeyfile = ",  str_namekeyfile);////
		 	
		 		str_pathkey = path_de +str_namekeyfile;
		 		if(str_loaimahoa.equalsIgnoreCase(PUBLIC_KEY)) // neu ng gui dung public key gui, su dung file key khac
		 		{
		 			flag_decrypt_pri = true;
		 			savedirsub = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC);
			 		if(!savedirsub.isDirectory())
			 		{
							savedirsub.mkdirs();
							Log.v(tag,"tao thu muc");
			 		}
					String path_key_pri = Environment.getExternalStorageDirectory().getAbsolutePath()+PATH_PUBLIC+str_nguoigui+" keypri.key";////
					Log.v(tag, "path_key_pri = "+path_key_pri);////
					str_pathkey = path_key_pri;
		 			
		 		}
				Log.v(tag, "file key save : " + str_pathkey);
				File f = new File(str_pathkey);
		        if(!f.isFile())
		        {
		        	progress = getResources().getString(R.string.dec_notkey_getkey);
		        	progress2 =getResources().getString(R.string.getkey_suc);
		        	flag_getkey = true;
		        	Log.v(tag+"::encrypt_action", "chua co key, xin key");
		        	
		        }
		        else
		        {
		        	Log.v(tag+"::encrypt_action", "thuc hien giai ma");
		        	progress = getResources().getString(R.string.dec_doinng);
		        	progress2 = getResources().getString(R.string.dec_suc);
		        	flag_getkey = false;
		        }
		        new sync_decryptFile().execute("decryptFile");
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag, "decrypt file action" + e.toString());
		}
		
	}
	
	private class sync_decryptFile extends AsyncTask<String, String, String>
	{
		
		ProgressDialog p = new ProgressDialog(attach_download_Activity.this);
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			p.setMessage(progress);
			p.show();
		}
		@Override
		protected String doInBackground(String... params) {
			// TODO Auto-generated method stub
			if(flag_getkey)
			{
				getkey_decryptFile();
			}
			else
			{
				giaimaFile();
			}
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			p.dismiss();
			st.showmess(progress2);
			if(flag_getkey) // sau khi xin key thuc hien giai ma truc tiep, tranh truong hop dang xin key cho ma hoa de tien hanh check sign
			{
				progress = "xin key thanh cong, tien hanh giai ma";
				decryptFile_action();
			}
			
			super.onPostExecute(result);
		}
	
	}
	public void getkey_decryptFile() //get key de ma hoa
	{
		try 
		{
			webserviceRequest webservice;
			if(flag_decrypt_pri) // xin key bat doi xung
			{
				Log.v(tag, "file key chua ton tai , bat dau xin key private rsa");////
				webservice   = new  webserviceRequest(str_nguoigui_nguoinhan, "RSApi");
				webservice.requestMyRSAKey();
				Log.v(tag, "xin key thanh cong");
			}
			else  // xin key doi xung
			{
				Log.i(tag + " getkey_decrypt", "xin key ");
				webservice = new webserviceRequest(str_nguoigui_nguoinhan, str_loaimahoa);
				webservice.getkeyStringDecrypt();
				Log.i(tag + " getkey dec","Xin key success...");
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag + "::getkey_de", e.toString());
		}
	}
	
	public void giaimaFile()
	{
		try 
		{
			if(str_loaimahoa.equalsIgnoreCase(ENC_AES))
			{
				aes = new AESControl(mykey.getKeyAES(str_pathkey));
				aes.DecFile(Filein, Fileout);
				Log.v(tag, " giai ma file, giai ma file aes thanh cong");
			}
			if(str_loaimahoa.equalsIgnoreCase(ENC_DES))
			{
				des = new DEScontrol(mykey.getKeyAES(str_pathkey));
				des.decryptFile(Filein, Fileout);
				Log.v(tag, " giai ma file, giai ma file des thanh cong");
			}
			if(str_loaimahoa.equalsIgnoreCase(ENC_TDES))
			{
				tdes = new TripleDEScontrol(mykey.getKeyAES(str_pathkey));
				tdes.DecFile(Filein, Fileout);
				Log.v(tag, " giai ma file, giai ma file 3des thanh cong");
			}
			if(str_loaimahoa.equalsIgnoreCase(ENC_PUBLIC))
			{
				Log.v(tag, " giai ma file,giai ma file = private key");
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag +" giaimaFile", e.toString());
		}
	}
	
	public int check_File_encrypt()// kiem tra trong nhung file down ve co file nao ma hoa ko
	{
		int i = 0;
		try 
		{
			for(String str : array_attach)
			{
				String s1 = str.substring(str.length() - 4); //lay 4 ky tu duoi
				if(s1.equalsIgnoreCase(ENC1) || s1.equalsIgnoreCase(ENC2)
						||s1.equalsIgnoreCase(ENC3) || s1.equalsIgnoreCase(ENC4))
				{
					i ++;
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
			Log.e(tag, " check file encrypt: "+e.toString() );
		}
		Log.v(tag, "check File encrypt : so file:" + i);
		return i;
	}
	
	public void convert_str_loaimahoa() // chuyen doi enc1 thanh des, enc3 thanh aes...
	{
		if(str_loaimahoa.equalsIgnoreCase(ENC1))
			str_loaimahoa = ENC_DES;
		if(str_loaimahoa.equalsIgnoreCase(ENC2))
			str_loaimahoa = ENC_TDES;
		if(str_loaimahoa.equalsIgnoreCase(ENC3))
			str_loaimahoa = ENC_AES;
		if(str_loaimahoa.equalsIgnoreCase(ENC4))
			str_loaimahoa = ENC_PUBLIC;
	}
}
